<template>
  <div class="users">
    <div class="page-header">
      <h2>用户管理</h2>
      <div class="header-actions">
        <button class="btn" @click="showBatchAdd = true">批量添加</button>
        <button class="btn" @click="showAddUser = true">添加用户</button>
      </div>
    </div>

    <!-- 搜索和分页控制 -->
    <div class="search-section card">
      <div class="search-form">
        <div class="form-group">
          <label>用户名</label>
          <input 
            type="text" 
            class="form-control" 
            v-model="searchForm.name" 
            placeholder="请输入用户名搜索"
          />
        </div>
        <div class="form-group">
          <label>每页显示</label>
          <select class="form-control" v-model="searchForm.pageSize">
            <option value="10">10条</option>
            <option value="20">20条</option>
            <option value="50">50条</option>
          </select>
        </div>
        <div class="form-actions">
          <button class="btn" @click="searchUsers">搜索</button>
          <button class="btn" @click="resetSearch">重置</button>
        </div>
      </div>
    </div>

    <div class="card">
      <table class="table">
        <thead>
          <tr>
            <th>ID</th>
            <th>用户名</th>
            <th>密码</th>
            <th>创建时间</th>
            <th>操作</th>
          </tr>
        </thead>
        <tbody>
          <tr v-for="user in users" :key="user.id">
            <td>{{ user.id }}</td>
            <td>{{ user.name }}</td>
            <td>
              <span class="password-field">
                {{ showPassword ? user.pwd : '••••••••' }}
                <button 
                  class="toggle-password" 
                  @click="togglePassword(user.id)"
                  :title="showPassword ? '隐藏密码' : '显示密码'"
                >
                  <i :class="showPassword ? 'fas fa-eye-slash' : 'fas fa-eye'"></i>
                </button>
              </span>
            </td>
            <td>{{ user.createdAt }}</td>
            <td>
              <button class="btn" @click="getUserById(user.id)">查看</button>
              <button class="btn" @click="editUser(user)">编辑</button>
              <button class="btn btn-danger" @click="deleteUserById(user.id)">删除</button>
            </td>
          </tr>
        </tbody>
      </table>
      <!-- 分页控制 -->
      <div class="pagination">
        <button 
          class="btn" 
          :disabled="currentPage <= 1" 
          @click="changePage(currentPage - 1)"
        >
          上一页
        </button>
        <span class="page-info">
          第 {{ currentPage }} 页，共 {{ totalPages }} 页，总计 {{ total }} 条记录
        </span>
        <button 
          class="btn" 
          :disabled="currentPage >= totalPages" 
          @click="changePage(currentPage + 1)"
        >
          下一页
        </button>
        <!-- 跳转到指定页码 -->
        <input type="number" min="1" :max="totalPages" v-model.number="jumpPage" class="jump-input" style="width:60px;margin:0 8px;" @keyup.enter="jumpToPage" />
        <button class="btn" @click="jumpToPage" :disabled="!jumpPage || jumpPage < 1 || jumpPage > totalPages">跳转</button>
        <!-- 每页条数选择 -->
        <select v-model.number="searchForm.pageSize" @change="changePageSize" class="page-size-select" style="margin-left:12px;">
          <option :value="10">10条/页</option>
          <option :value="20">20条/页</option>
          <option :value="50">50条/页</option>
          <option :value="100">100条/页</option>
        </select>
      </div>
    </div>

    <!-- 添加/编辑用户弹窗 -->
    <div v-if="showAddUser || editingUser" class="modal-overlay" @click="closeModal">
      <div class="modal" @click.stop>
        <h3>{{ editingUser ? '编辑用户' : '添加用户' }}</h3>
        <form @submit.prevent="saveUser">
          <div class="form-group">
            <label>用户名</label>
            <input 
              type="text" 
              class="form-control" 
              v-model="userForm.name" 
              required
              placeholder="请输入用户名"
            />
          </div>
          <div class="form-group">
            <label>密码</label>
            <div class="password-input-group">
              <input 
                :type="showPasswordInput ? 'text' : 'password'" 
                class="form-control" 
                v-model="userForm.pwd" 
                required
                placeholder="请输入密码"
              />
              <button 
                type="button"
                class="toggle-password-input" 
                @click="togglePasswordInput"
                :title="showPasswordInput ? '隐藏密码' : '显示密码'"
              >
                <i :class="showPasswordInput ? 'fas fa-eye-slash' : 'fas fa-eye'"></i>
              </button>
            </div>
          </div>
          <div class="form-group" v-if="!editingUser">
            <label>确认密码</label>
            <div class="password-input-group">
              <input 
                :type="showConfirmPasswordInput ? 'text' : 'password'" 
                class="form-control" 
                v-model="confirmPassword" 
                required
                placeholder="请再次输入密码"
              />
              <button 
                type="button"
                class="toggle-confirm-password-input" 
                @click="toggleConfirmPasswordInput"
                :title="showConfirmPasswordInput ? '隐藏密码' : '显示密码'"
              >
                <i :class="showConfirmPasswordInput ? 'fas fa-eye-slash' : 'fas fa-eye'"></i>
              </button>
            </div>
          </div>
          <div class="form-actions">
            <button type="button" class="btn" @click="closeModal">取消</button>
            <button type="submit" class="btn">保存</button>
          </div>
        </form>
      </div>
    </div>

    <!-- 批量添加弹窗 -->
    <div v-if="showBatchAdd" class="modal-overlay" @click="closeBatchModal">
      <div class="modal" @click.stop>
        <h3>批量添加用户</h3>
        <form @submit.prevent="saveBatchUsers">
          <div class="form-group">
            <label>用户数据（JSON格式）</label>
            <textarea 
              class="form-control" 
              v-model="batchUserData"
              rows="10"
              placeholder='[{"name":"user1","pwd":"password1"},{"name":"user2","pwd":"password2"}]'
            ></textarea>
          </div>
          <div class="form-actions">
            <button type="button" class="btn" @click="closeBatchModal">取消</button>
            <button type="submit" class="btn">批量添加</button>
          </div>
        </form>
      </div>
    </div>

    <!-- 用户详情弹窗 -->
    <div v-if="showUserDetail" class="modal-overlay" @click="closeDetailModal">
      <div class="modal" @click.stop>
        <h3>用户详情</h3>
        <div class="user-detail">
          <div class="detail-item">
            <label>ID：</label>
            <span>{{ selectedUser.id }}</span>
          </div>
          <div class="detail-item">
            <label>用户名：</label>
            <span>{{ selectedUser.name }}</span>
          </div>
          <div class="detail-item">
            <label>密码：</label>
            <span>{{ selectedUser.pwd }}</span>
          </div>
          <div class="detail-item">
            <label>创建时间：</label>
            <span>{{ selectedUser.createdAt }}</span>
          </div>
        </div>
        <div class="form-actions">
          <button type="button" class="btn" @click="closeDetailModal">关闭</button>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
export default {
  name: 'Users',
  data() {
    return {
      users: [],
      showAddUser: false,
      editingUser: null,
      showBatchAdd: false,
      showUserDetail: false,
      selectedUser: {},
      showPassword: false,
      showPasswordInput: false,
      showConfirmPasswordInput: false,
      userForm: {
        name: '',
        pwd: ''
      },
      confirmPassword: '',
      batchUserData: '',
      searchForm: {
        name: '',
        pageSize: 10,
        currentPage: 1
      },
      currentPage: 1,
      totalPages: 1,
      total: 0,
      loading: false,
      jumpPage: 1,
      // API基础路径配置
      apiBaseUrl: '/user'
    }
  },
  mounted() {
    console.log('组件挂载，开始检测网络状态...')
    this.checkNetworkStatus()
    this.loadDataList()
  },
  methods: {
    // 网络状态检测
    async checkNetworkStatus() {
      try {
        console.log('检测后端服务状态...')
        const response = await fetch(`${this.apiBaseUrl}/loadDataList`, {
          method: 'POST',
          headers: {
            'Content-Type': 'application/json'
          },
          body: JSON.stringify({
            nameFuzzy: '',
            simplePage: {
              start: 0,
              end: 1
            }
          })
        })
        
        if (response.ok) {
          console.log('✅ 后端服务正常')
        } else {
          console.warn('⚠️ 后端服务响应异常，状态码:', response.status)
        }
      } catch (error) {
        console.error('❌ 后端服务连接失败:', error.message)
      }
    },
    // API调用方法
    async loadDataList() {
      try {
        this.loading = true
        // 只传pageNo和pageSize，适配后端UserQuery分页逻辑
        const requestBody = {
          nameFuzzy: this.searchForm.name || '',
          pageNo: this.currentPage,
          pageSize: this.searchForm.pageSize
        }
        
        console.log('🔄 开始加载用户数据...')
        console.log('📤 查询请求数据:', JSON.stringify(requestBody, null, 2))
        console.log('🌐 请求URL:', `${this.apiBaseUrl}/loadDataList`)
        
        const response = await fetch(`${this.apiBaseUrl}/loadDataList`, {
          method: 'POST',
          headers: {
            'Content-Type': 'application/json',
            'Accept': 'application/json'
          },
          body: JSON.stringify(requestBody)
        })
        
        console.log('📥 查询响应状态:', response.status)
        console.log('📥 查询响应头:', Object.fromEntries(response.headers.entries()))
        
        if (!response.ok) {
          const errorText = await response.text()
          console.error('❌ 查询HTTP错误:', response.status, errorText)
          throw new Error(`HTTP error! status: ${response.status}, message: ${errorText}`)
        }
        
        const responseText = await response.text()
        console.log('📥 查询响应内容:', responseText)
        
        let data
        try {
          data = JSON.parse(responseText)
          console.log('📥 查询解析后的数据:', data)
        } catch (parseError) {
          console.error('❌ 查询JSON解析失败:', parseError)
          throw new Error('响应数据格式错误，不是有效的JSON')
        }
        
        // 适配后端返回的数据格式
        if (data.status === 'success' || data.success) {
          // 后端返回的数据结构
          const responseData = data.data || data
          this.users = responseData.list || responseData || []
          this.total = responseData.totalCount || responseData.total || this.users.length
          this.totalPages = Math.ceil(this.total / this.searchForm.pageSize)
          
          console.log('✅ 数据加载成功')
          console.log('📊 用户列表:', this.users)
          console.log('📊 总数:', this.total)
          console.log('📊 总页数:', this.totalPages)
        } else {
          console.error('❌ 数据加载失败:', data.info || data.message)
          alert('加载数据失败：' + (data.info || data.message))
        }
      } catch (error) {
        console.error('❌ 加载数据异常:', error)
        
        // 如果是网络错误，显示更友好的提示
        if (error.name === 'TypeError' && error.message.includes('fetch')) {
          alert('网络连接失败，请检查后端服务是否正常运行')
        } else {
          alert('加载数据失败：' + error.message)
        }
        
        // 模拟数据，实际使用时删除
        console.log('📝 使用模拟数据')
        this.users = [
          { id: 1, name: 'admin', pwd: 'admin123', createdAt: '2023-01-15' },
          { id: 2, name: 'user1', pwd: 'password123', createdAt: '2023-02-20' },
          { id: 3, name: 'testuser', pwd: 'test123', createdAt: '2023-03-10' }
        ]
        this.total = 3
        this.totalPages = 1
      } finally {
        this.loading = false
      }
    },

    async addUser(userData) {
      try {
        if (!userData.name || !userData.pwd) {
          alert('用户名和密码不能为空！');
          return;
        }

        // 用表单格式发送
        const formData = new URLSearchParams();
        formData.append('name', userData.name.trim());
        formData.append('pwd', userData.pwd.trim());

        console.log('🚀 发送添加用户请求...');
        console.log('📤 表单数据:', formData.toString());
        console.log('🌐 请求URL:', `${this.apiBaseUrl}/add`);

        const response = await fetch(`${this.apiBaseUrl}/add`, {
          method: 'POST',
          headers: {
            'Content-Type': 'application/x-www-form-urlencoded',
            'Accept': 'application/json'
          },
          body: formData
        });

        console.log('📥 响应状态:', response.status);
        console.log('📥 响应头:', Object.fromEntries(response.headers.entries()));

        const responseText = await response.text();
        console.log('📥 响应内容:', responseText);

        let data;
        try {
          data = JSON.parse(responseText);
          console.log('📥 解析后的数据:', data);
        } catch (parseError) {
          console.error('❌ JSON解析失败:', parseError);
          throw new Error('响应数据格式错误，不是有效的JSON');
        }

        if (data.status === 'success' || data.success) {
          console.log('✅ 添加用户成功');
          alert('添加用户成功！');
          this.loadDataList();
        } else {
          const errorMsg = data.info || data.message || '添加用户失败';
          console.error('❌ 添加用户失败:', errorMsg);
          alert('添加用户失败：' + errorMsg);
        }
      } catch (error) {
        console.error('❌ 添加用户异常:', error);
        alert('添加用户失败：' + error.message);
      }
    },

    async addBatchUsers(userList) {
      try {
        // 直接发送用户列表，匹配后端List<User>的格式
        const response = await fetch(`${this.apiBaseUrl}/addBatch`, {
          method: 'POST',
          headers: {
            'Content-Type': 'application/json'
          },
          body: JSON.stringify(userList)
        })
        
        if (!response.ok) {
          throw new Error(`HTTP error! status: ${response.status}`)
        }
        
        const data = await response.json()
        if (data.status === 'success' || data.success) {
          alert('批量添加用户成功！')
          this.loadDataList()
        } else {
          alert('批量添加用户失败：' + (data.info || data.message))
        }
      } catch (error) {
        console.error('批量添加用户失败：', error)
        alert('批量添加用户失败，请检查网络连接或后端服务是否正常')
      }
    },

    async addOrUpdateBatchUsers(userList) {
      try {
        // 直接发送用户列表，匹配后端List<User>的格式
        const response = await fetch(`${this.apiBaseUrl}/addOrUpdateBatch`, {
          method: 'POST',
          headers: {
            'Content-Type': 'application/json'
          },
          body: JSON.stringify(userList)
        })
        
        if (!response.ok) {
          throw new Error(`HTTP error! status: ${response.status}`)
        }
        
        const data = await response.json()
        if (data.status === 'success' || data.success) {
          alert('批量添加/修改用户成功！')
          this.loadDataList()
        } else {
          alert('批量添加/修改用户失败：' + (data.info || data.message))
        }
      } catch (error) {
        console.error('批量添加/修改用户失败：', error)
        alert('批量添加/修改用户失败，请检查网络连接或后端服务是否正常')
      }
    },

    async getUserById(id) {
      try {
        const response = await fetch(`${this.apiBaseUrl}/getUserById?id=${id}`)
        
        if (!response.ok) {
          throw new Error(`HTTP error! status: ${response.status}`)
        }
        
        const data = await response.json()
        if (data.status === 'success' || data.success) {
          this.selectedUser = data.data || data
          this.showUserDetail = true
        } else {
          alert('获取用户详情失败：' + (data.info || data.message))
        }
      } catch (error) {
        console.error('获取用户详情失败：', error)
        // 模拟数据
        this.selectedUser = this.users.find(u => u.id === id) || {}
        this.showUserDetail = true
      }
    },

    async updateUserById(userData) {
      try {
        const formData = new URLSearchParams();
        formData.append('id', userData.id);
        formData.append('name', userData.name.trim());
        formData.append('pwd', userData.pwd.trim());

        const response = await fetch(`${this.apiBaseUrl}/updateUserById`, {
          method: 'POST',
          headers: {
            'Content-Type': 'application/x-www-form-urlencoded'
          },
          body: formData
        });

        if (!response.ok) {
          throw new Error(`HTTP error! status: ${response.status}`);
        }

        const data = await response.json();
        if (data.status === 'success' || data.success) {
          alert('更新用户成功！');
          this.loadDataList();
        } else {
          alert('更新用户失败：' + (data.info || data.message));
        }
      } catch (error) {
        console.error('更新用户失败：', error);
        alert('更新用户失败，请检查网络连接或后端服务是否正常');
      }
    },

    async deleteUserById(id) {
      if (!confirm('确定要删除这个用户吗？')) {
        return
      }
      
      try {
        const response = await fetch(`${this.apiBaseUrl}/deleteUserById?id=${id}`, {
          method: 'POST',
          headers: {
            'Content-Type': 'application/json'
          }
        })
        
        if (!response.ok) {
          throw new Error(`HTTP error! status: ${response.status}`)
        }
        
        const data = await response.json()
        if (data.status === 'success' || data.success) {
          alert('删除用户成功！')
          this.loadDataList()
        } else {
          alert('删除用户失败：' + (data.info || data.message))
        }
      } catch (error) {
        console.error('删除用户失败：', error)
        alert('删除用户失败，请检查网络连接或后端服务是否正常')
      }
    },

    // 界面交互方法
    togglePassword(userId) {
      this.showPassword = !this.showPassword
    },
    togglePasswordInput() {
      this.showPasswordInput = !this.showPasswordInput
    },
    toggleConfirmPasswordInput() {
      this.showConfirmPasswordInput = !this.showConfirmPasswordInput
    },
    editUser(user) {
      this.editingUser = user
      this.userForm = { ...user }
      this.confirmPassword = ''
    },
    searchUsers() {
      this.currentPage = 1
      this.loadDataList()
    },
    resetSearch() {
      this.searchForm = {
        name: '',
        pageSize: 10,
        currentPage: 1
      }
      this.currentPage = 1
      this.loadDataList()
    },
    changePage(page) {
      if (page < 1 || page > this.totalPages) return;
      this.currentPage = page;
      this.jumpPage = page;
      this.loadDataList();
    },
    jumpToPage() {
      if (!this.jumpPage || this.jumpPage < 1 || this.jumpPage > this.totalPages) return;
      this.changePage(this.jumpPage);
    },
    changePageSize() {
      this.currentPage = 1;
      this.jumpPage = 1;
      this.loadDataList();
    },
    saveUser() {
      // 验证密码
      if (!this.editingUser && this.userForm.pwd !== this.confirmPassword) {
        alert('两次输入的密码不一致！')
        return
      }
      
      if (this.editingUser) {
        // 编辑用户
        this.updateUserById(this.userForm)
      } else {
        // 添加用户
        this.addUser(this.userForm)
      }
      this.closeModal()
    },
    saveBatchUsers() {
      try {
        const userList = JSON.parse(this.batchUserData)
        if (!Array.isArray(userList)) {
          alert('请输入正确的JSON数组格式！')
          return
        }
        
        // 检查数据格式是否正确
        const isValidFormat = userList.every(item => 
          item.name && item.pwd
        )
        
        if (!isValidFormat) {
          alert('数据格式错误！每个用户数据应该包含name和pwd字段')
          return
        }
        
        this.addBatchUsers(userList)
        this.closeBatchModal()
      } catch (error) {
        alert('JSON格式错误，请检查输入！')
      }
    },
    closeModal() {
      this.showAddUser = false
      this.editingUser = null
      this.userForm = {
        name: '',
        pwd: ''
      }
      this.confirmPassword = ''
      this.showPasswordInput = false
      this.showConfirmPasswordInput = false
    },
    closeBatchModal() {
      this.showBatchAdd = false
      this.batchUserData = ''
    },
    closeDetailModal() {
      this.showUserDetail = false
      this.selectedUser = {}
    },
    // 测试不同的请求格式
    async testAddUser(userData) {
      console.log('🧪 开始测试不同的请求格式...')
      
      // 测试1：直接参数
      try {
        const response1 = await fetch(`${this.apiBaseUrl}/add?name=${userData.name}&pwd=${userData.pwd}`, {
          method: 'POST',
          headers: {
            'Accept': 'application/json'
          }
        })
        console.log('📥 测试1 (GET参数) 响应:', response1.status)
        if (response1.ok) {
          const data = await response1.json()
          console.log('✅ 测试1成功:', data)
          return true
        }
      } catch (error) {
        console.log('❌ 测试1失败:', error.message)
      }
      
      // 测试2：JSON格式
      try {
        const response2 = await fetch(`${this.apiBaseUrl}/add`, {
          method: 'POST',
          headers: {
            'Content-Type': 'application/json',
            'Accept': 'application/json'
          },
          body: JSON.stringify({
            name: userData.name,
            pwd: userData.pwd
          })
        })
        console.log('📥 测试2 (JSON) 响应:', response2.status)
        if (response2.ok) {
          const data = await response2.json()
          console.log('✅ 测试2成功:', data)
          return true
        }
      } catch (error) {
        console.log('❌ 测试2失败:', error.message)
      }
      
      // 测试3：表单格式
      try {
        const formData = new URLSearchParams()
        formData.append('name', userData.name)
        formData.append('pwd', userData.pwd)
        
        const response3 = await fetch(`${this.apiBaseUrl}/add`, {
          method: 'POST',
          headers: {
            'Content-Type': 'application/x-www-form-urlencoded',
            'Accept': 'application/json'
          },
          body: formData
        })
        console.log('📥 测试3 (表单) 响应:', response3.status)
        if (response3.ok) {
          const data = await response3.json()
          console.log('✅ 测试3成功:', data)
          return true
        }
      } catch (error) {
        console.log('❌ 测试3失败:', error.message)
      }
      
      return false
    }
  }
}
</script>

<style scoped>
.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.page-header h2 {
  margin: 0;
  color: #2c3e50;
}

.header-actions {
  display: flex;
  gap: 10px;
}

.search-section {
  margin-bottom: 20px;
}

.search-form {
  display: flex;
  gap: 20px;
  align-items: end;
  flex-wrap: wrap;
}

.search-form .form-group {
  flex: 1;
  min-width: 200px;
}

.pagination {
  display: flex;
  justify-content: center;
  align-items: center;
  gap: 20px;
  margin-top: 20px;
  padding: 20px 0;
}

.page-info {
  color: #7f8c8d;
  font-size: 14px;
}

.user-detail {
  margin-bottom: 20px;
}

.detail-item {
  display: flex;
  margin-bottom: 15px;
  padding: 10px;
  background: #f8f9fa;
  border-radius: 4px;
}

.detail-item label {
  font-weight: 600;
  min-width: 100px;
  color: #2c3e50;
}

.detail-item span {
  color: #34495e;
}

.password-field {
  display: flex;
  align-items: center;
  gap: 8px;
}

.toggle-password {
  background: none;
  border: none;
  color: #3498db;
  cursor: pointer;
  padding: 2px;
  border-radius: 4px;
  transition: all 0.3s ease;
}

.toggle-password:hover {
  background: #f8f9fa;
  color: #2980b9;
}

.password-input-group {
  position: relative;
  display: flex;
  align-items: center;
}

.toggle-password-input,
.toggle-confirm-password-input {
  position: absolute;
  right: 10px;
  top: 50%;
  transform: translateY(-50%);
  background: none;
  border: none;
  color: #7f8c8d;
  cursor: pointer;
  padding: 4px;
  border-radius: 4px;
  transition: all 0.3s ease;
}

.toggle-password-input:hover,
.toggle-confirm-password-input:hover {
  color: #3498db;
  background: #f8f9fa;
}

.password-input-group .form-control {
  padding-right: 40px;
}

.modal-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.5);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 1000;
}

.modal {
  background: white;
  padding: 30px;
  border-radius: 8px;
  width: 500px;
  max-width: 90vw;
  max-height: 90vh;
  overflow-y: auto;
}

.modal h3 {
  margin-bottom: 20px;
  color: #2c3e50;
}

.form-actions {
  display: flex;
  gap: 10px;
  justify-content: flex-end;
  margin-top: 20px;
}

/* 密码字段样式 */
.password-field {
  font-family: 'Courier New', monospace;
  font-weight: bold;
  color: #2c3e50;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .search-form {
    flex-direction: column;
  }
  
  .search-form .form-group {
    min-width: auto;
  }
  
  .header-actions {
    flex-direction: column;
    gap: 5px;
  }
}
</style> 